package com.hdu.h_health.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hdu.h_health.Adapter.CommentAdapter;
import com.hdu.h_health.R;
import com.hdu.h_health.bean.Comment;
import com.hdu.h_health.bean.Secret;
import com.hdu.h_health.bean.User;
import com.hdu.h_health.common.BaseActivity;
import com.hdu.h_health.dependence.xlistview.XListView;
import com.hdu.h_health.model.CommentModel;
import com.hdu.h_health.model.SecretModel;
import com.hdu.h_health.model.UserModel;
import com.hdu.h_health.utils.CommonUtils;
import com.hdu.h_health.utils.ViewUtils;
import com.hdu.h_health.widget.NavigationView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * 心事详情页
 * Created by 612 on 2016/3/22.
 */
public class CommentActivity extends BaseActivity implements View.OnClickListener, XListView.IXListViewListener, View.OnTouchListener {

    @Bind(R.id.navView)
    NavigationView navView;
    private Secret secret;//心事
    private ImageView avatar;//用户头像
    private TextView tv_time;//时间
    private TextView username;//用户名（用户昵称）
    private TextView tv_content;//心事内容
    private LinearLayout commentNumber;//评论数
    private TextView error;//错误反馈

    private XListView xListView;
    private ProgressBar proBar;
    private LinearLayout area_commit;

    private List<Comment> comments = new ArrayList<Comment>();//评论列表
    private CommentAdapter adapter;
    private EditText commentContent;//评论内容
    private Button btn_comment;//提交评论

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取传递过来的对象
        secret = (Secret) getIntent().getSerializableExtra("secret");
        setContentView(R.layout.activity_commont);

        xListView.setXListViewListener(this);
        xListView.setPullLoadEnable(true);//设置是否可以上拉加载更多
        xListView.setOnTouchListener(this);
        queryComment(0, STATE_REFRESH);

        navView.setTv_title("心事详情");
        navView.getIv_left().setImageResource(R.drawable.ic_keyboard_arrow_left_white_36dp);
        navView.getIv_right().setImageResource(R.drawable.ic_control_point_white_36dp);
        navView.setClickListener(new NavigationView.ClickCallBack() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
                //检查是否登录
                boolean isLogin = UserModel.getInstance().checkIsLogin(getBaseContext());
                if (!isLogin) {
                    CommonUtils.showToast(getBaseContext(), "请先登录！");
                    startActivity(new Intent(getBaseContext(), LoginActivity.class));
                    return;
                }
                startActivity(new Intent(getBaseContext(), EditSecretActivity.class));
            }
        });
    }

    //初始化布局
    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        proBar = (ProgressBar) findViewById(R.id.progressbar);
        error = (TextView) findViewById(R.id.error);
        area_commit = (LinearLayout) findViewById(R.id.area_commit);
        commentContent = (EditText) findViewById(R.id.comment_content);
        btn_comment = (Button) findViewById(R.id.btn_comment);
        btn_comment.setOnClickListener(this);

        xListView = (XListView) findViewById(R.id.lv_comment);
        adapter = new CommentAdapter(this, comments);
        xListView.setAdapter(adapter);

        //添加头部布局（前面必须先设置adapter,要不不会显示）
        View headView = getLayoutInflater().inflate(R.layout.item_content_second, null);

        xListView.addHeaderView(headView);

        avatar = (ImageView) headView.findViewById(R.id.iv_avatar);
        username = (TextView) headView.findViewById(R.id.username);
        tv_content = (TextView) headView.findViewById(R.id.tv_content);
        tv_time = (TextView) headView.findViewById(R.id.tv_time);
        commentNumber = (LinearLayout) headView.findViewById(R.id.layout_comment);
        //详情页隐藏评论数
        commentNumber.setVisibility(View.GONE);

        //设置头像，昵称，心事内容
        ViewUtils.setPic(secret.getAuthor().getAvatar(), R.mipmap.head, avatar);
        if (secret.getAuthor().getNick().isEmpty()) {
            username.setText(secret.getAuthor().getUsername());
        } else {
            username.setText(secret.getAuthor().getNick());
        }


        tv_content.setText(secret.getContent());
        tv_time.setText(secret.getCreatedAt());
    }

    //点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_comment:
                addComment();
                commentContent.setText("");//重新设置为空
                break;
            default:
                break;
        }
    }

    // 当前页的编号，从0开始
    private int curPage = 0;

    //下拉刷新
    @Override
    public void onRefresh() {
        curPage = 0;
        queryComment(curPage, STATE_REFRESH);
        stopLoad();
    }

    //上拉加载
    @Override
    public void onLoadMore() {
        curPage++;
        queryComment(curPage, STATE_MORE);
        stopLoad();
    }

    //停止刷新
    private void stopLoad() {
        xListView.stopRefresh();//停止下拉刷新
        xListView.stopLoadMore();//停止上拉加载
        xListView.setRefreshTime(R.string.xlistview_time);//设置刷新时间
    }

    //添加评论
    private void addComment() {
        String content = commentContent.getText().toString();
        User user = BmobUser.getCurrentUser(this, User.class);
        final Comment comment = new Comment();
        if (TextUtils.isEmpty(content)) {
            CommonUtils.showToast(this, "评论不能为空！");
            return;
        }
        if (user == null) {
            CommonUtils.showToast(this, "请先登录！");
            return;
        }
        CommentModel.getInstance().addComment(this, content, user, comment, new SaveListener() {
            @Override
            public void onSuccess() {
                CommonUtils.showToast(getBaseContext(), "评论成功");
                CommonUtils.showLog("评论成功");
                //添加心事与评论的关系（一对多）
                SecretModel.getInstance().addCommentRelation(getBaseContext(), secret, comment);
                queryComment(0, STATE_REFRESH);
            }

            @Override
            public void onFailure(int i, String s) {
                CommonUtils.showToast(getBaseContext(), "评论失败");
                CommonUtils.showLog("评论失败" + i + s);
            }
        });
    }

    private static final int STATE_REFRESH = 0;// 下拉刷新
    private static final int STATE_MORE = 1;// 加载更多

    private static final int LIMIT = 5;

    //查询评论
    private void queryComment(final int page, final int type) {
        if (secret == null) {
            CommonUtils.showLog("secret为空");
            return;
        }
        BmobQuery<Comment> query = new BmobQuery<Comment>();
        query.setLimit(LIMIT);//查询数量
        query.setSkip(LIMIT * page);//分页查询
        query.addWhereRelatedTo("commentRe", new BmobPointer(secret));
        query.order("-createdAt");//查询排序
        query.include("author");
        query.findObjects(getBaseContext(), new FindListener<Comment>() {
            @Override
            public void onSuccess(List<Comment> list) {
                if (list.size() > 0) {
                    if (type == STATE_REFRESH) {
                        comments.clear();
                    }
                    comments.addAll(list);
                    adapter.notifyDataSetChanged();
                    CommonUtils.showLog("查询评论成功！" + list.size());
                } else if (type == STATE_MORE) {
                    CommonUtils.showToast(getBaseContext(), "没有更多评论");
                } else if (type == STATE_REFRESH) {
                    CommonUtils.showToast(getBaseContext(), "暂无评论");
                    error.setText("暂无评论");
                }
                proBar.setVisibility(View.GONE);
            }

            @Override
            public void onError(int i, String s) {
                proBar.setVisibility(View.GONE);
                CommonUtils.showLog(i + s);
            }
        });
    }

    private float firstY = 0, lastY = 0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                firstY = event.getY();
                area_commit.setVisibility(View.GONE);
                break;
            case MotionEvent.ACTION_MOVE:
                lastY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                if (lastY - firstY > 0 && Math.abs(lastY - firstY) > 25) {//上滑
                    area_commit.setVisibility(View.VISIBLE);
                } else if (lastY - firstY < 0 && Math.abs(lastY - firstY) > 25) {//下滑
                    area_commit.setVisibility(View.GONE);
                }
                break;
        }
        return false;
    }
}
